package jobserver

import "time"

type JobScheduler struct {
	name     string
	interval time.Duration
	timeout  time.Duration
	stopCh   chan int

	jobEntity IJob
}

func NewJobScheduler(name string, interval time.Duration, f IJob) *JobScheduler {
	return &JobScheduler{
		name:      name,
		interval:  interval,
		stopCh:    make(chan int),
		jobEntity: f,
	}
}

func (sch *JobScheduler) Name() string {
	return sch.name
}

func (sch *JobScheduler) Run() error {
	sch.run()
	return nil
}

func (sch *JobScheduler) run() {
	if sch.interval <= 0 {
		return
	}
	timer := time.NewTicker(sch.interval)

	for {
		select {
		case <-timer.C:
			sch.jobEntity.Run()
		case <-sch.stopCh:
			timer.Stop()
			return
		default:
		}
	}
}

func (sch *JobScheduler) Stop() error {
	sch.stopCh <- 0
	return nil
}
